package com.platform.oss.core.local;

import cn.hutool.core.io.FileUtil;
import com.platform.comm.util.StringPool;
import com.platform.comm.util.StringUtil;
import com.platform.oss.core.StandardOssClient;
import com.platform.oss.core.local.model.LocalOssConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author zq
 */
@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LocalOssClient implements StandardOssClient {

    /**
     * 获取uuid
     */
    private static final String UUID = uuid();

    private static final String uuid() {
        return java.util.UUID.randomUUID().toString().replace("-", "");
    }

    private LocalOssConfig localOssConfig;


    @Override
    public String upload(InputStream is, String targetFileName) {
        String key = getKey(generateFileName(targetFileName), true);
        log.info("本地上传方式:::key:::::"+key);
        FileUtil.writeFromStream(is, key);
        return key;
    }

    @SneakyThrows
    public String generateFileName(String targetFileName) {
        String suffix = targetFileName.substring(targetFileName.lastIndexOf(".") + 1);
        // 上传文件名处理
        String filename = StringUtil.getUUID();
        if (suffix.startsWith(StringPool.DOT)) {
            filename += suffix;
        } else {
            filename += StringPool.DOT + suffix;
        }
        return filename;
    }

    @Override
    public InputStream download(String fileId) {
        log.info("本地下载方式:::::::::::::::::::::::::"+fileId);
        return FileUtil.getInputStream(fileId);
    }

    @Override
    public void downLoad(OutputStream os, String targetName) {
        FileUtil.writeToStream(getKey(targetName, true), os);
    }

    @Override
    public void delete(String targetName) {
        FileUtil.del(getKey(targetName, true));
    }

    @Override
    public String getBasePath() {
        String basePath = localOssConfig.getBasePath();
        if (!FileUtil.exist(basePath)) {
            FileUtil.mkdir(basePath);
        }
        return basePath;
    }

}
